/**
 * 智慧粮仓系统 - UI组件库
 * 包含所有可重用的UI组件和界面元素
 * 
 * 组件使用说明：
 * 
 * 1. 基础模态框：
 *    showCommonModal({
 *        title: '标题',
 *        content: '内容HTML或DOM元素',
 *        buttons: [{text: '确定', class: 'btn-primary', click: function(){}}],
 *        size: 'small|medium|large'
 *    });
 * 
 * 2. 确认对话框：
 *    showConfirmDialog({
 *        message: '确认信息',
 *        onConfirm: function() { console.log('确认'); },
 *        onCancel: function() { console.log('取消'); }
 *    });
 * 
 * 3. 表单模态框：
 *    showFormModal({
 *        title: '表单标题',
 *        fields: [
 *            {name: 'username', label: '用户名', type: 'text', required: true},
 *            {name: 'email', label: '邮箱', type: 'email', required: true},
 *            {name: 'type', label: '类型', type: 'select', options: ['选项1', '选项2']}
 *        ],
 *        onSubmit: function(formData) { console.log(formData); }
 *    });
 * 
 * 4. 信息提示框：
 *    showInfoDialog('操作成功', 'success');  // success, error, warning, info
 * 
 * 5. 加载模态框：
 *    const loadingModal = showLoadingModal('加载中...');
 *    closeModal(loadingModal);  // 关闭加载框
 * 
 * 6. 关闭模态框：
 *    closeModal();  // 关闭所有模态框
 *    closeModal(specificModal);  // 关闭指定模态框
 * 
 * 7. Toast消息：
 *    showToast('操作成功', 'success', 3000);  // success, warning, error, info
 */

/**
 * 显示Toast消息
 * @param {string} message 消息内容
 * @param {string} type 消息类型：success, warning, error, info
 * @param {number} duration 显示时长（毫秒）
 */
function showToast(message, type = '', duration = 3000) {
    let container = document.getElementById('toast-container');
    
    // 如果容器不存在，创建一个
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'toast-container';
        document.body.appendChild(container);
    }
    
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    // 添加图标
    let icon = '';
    if (type === 'success') {
        icon = '<i class="layui-icon layui-icon-ok"></i>';
    } else if (type === 'warning') {
        icon = '<i class="layui-icon layui-icon-tips"></i>';
    } else if (type === 'error') {
        icon = '<i class="layui-icon layui-icon-close"></i>';
    } else if (type === 'info') {
        icon = '<i class="layui-icon layui-icon-about"></i>';
    }
    
    toast.innerHTML = `${icon}<span>${message}</span>`;
    
    // 添加到容器
    container.appendChild(toast);
    
    // 设置动画
    setTimeout(() => {
        toast.style.transition = 'opacity 0.3s, transform 0.3s';
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(-10px)';
        
        // 移除元素
        setTimeout(() => {
            if (container.contains(toast)) {
                container.removeChild(toast);
            }
        }, 300);
    }, duration);
}

/**
 * 显示模态对话框
 * @param {string} title 标题
 * @param {string} content HTML内容
 * @param {function} onClose 关闭回调
 */
function showModal(title, content, onClose) {
    // 创建模态框元素
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
    modal.style.display = 'flex';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '2000';
    modal.style.backdropFilter = 'blur(8px)';
    modal.style.WebkitBackdropFilter = 'blur(8px)';
    
    // 创建模态框内容
    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    // 使用主题变量来设置背景色
    modalContent.style.backgroundColor = 'var(--theme-modal-bg)';
    modalContent.style.color = 'var(--theme-text-color)';
    modalContent.style.borderRadius = '16px';
    modalContent.style.boxShadow = '0 20px 60px rgba(0, 0, 0, 0.4), 0 8px 32px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1)';
    modalContent.style.width = '90%';
    modalContent.style.maxWidth = '480px';
    modalContent.style.maxHeight = '85vh';
    modalContent.style.overflow = 'hidden';
    modalContent.style.border = '1px solid var(--theme-card-border)';
    modalContent.style.backdropFilter = 'blur(20px)';
    modalContent.style.WebkitBackdropFilter = 'blur(20px)';
    
    // 创建模态框标题
    const modalHeader = document.createElement('div');
    modalHeader.className = 'modal-header';
    modalHeader.style.borderBottom = '1px solid var(--theme-card-border)';
    modalHeader.style.padding = '24px 28px 20px';
    modalHeader.style.display = 'flex';
    modalHeader.style.justifyContent = 'space-between';
    modalHeader.style.alignItems = 'center';
    modalHeader.style.background = 'linear-gradient(135deg, var(--theme-gradient-start) 0%, var(--theme-gradient-end) 100%)';
    
    const modalTitle = document.createElement('h3');
    modalTitle.textContent = title;
    modalTitle.style.margin = '0';
    modalTitle.style.fontSize = '20px';
    modalTitle.style.fontWeight = '600';
    modalTitle.style.color = 'var(--theme-text-color)';
    modalTitle.style.textShadow = '0 1px 3px rgba(0, 0, 0, 0.3)';
    
    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.background = 'rgba(255, 255, 255, 0.1)';
    closeBtn.style.border = 'none';
    closeBtn.style.fontSize = '24px';
    closeBtn.style.cursor = 'pointer';
    closeBtn.style.color = 'var(--theme-text-color)';
    closeBtn.style.width = '32px';
    closeBtn.style.height = '32px';
    closeBtn.style.display = 'flex';
    closeBtn.style.alignItems = 'center';
    closeBtn.style.justifyContent = 'center';
    closeBtn.style.borderRadius = '50%';
    closeBtn.style.opacity = '0.8';
    closeBtn.style.transition = 'all 0.2s ease';
    
    closeBtn.addEventListener('mouseenter', function() {
        this.style.opacity = '1';
        this.style.background = 'rgba(255, 255, 255, 0.2)';
        this.style.transform = 'scale(1.1)';
    });
    
    closeBtn.addEventListener('mouseleave', function() {
        this.style.opacity = '0.8';
        this.style.background = 'rgba(255, 255, 255, 0.1)';
        this.style.transform = 'scale(1)';
    });
    
    closeBtn.onclick = function() {
        document.body.removeChild(modal);
        if (onClose && typeof onClose === 'function') {
            onClose();
        }
    };
    
    modalHeader.appendChild(modalTitle);
    modalHeader.appendChild(closeBtn);
    modalContent.appendChild(modalHeader);
    
    // 创建模态框内容
    const modalBody = document.createElement('div');
    modalBody.className = 'modal-body';
    modalBody.style.padding = '28px';
    modalBody.style.maxHeight = 'calc(85vh - 160px)';
    modalBody.style.overflowY = 'auto';
    modalBody.style.color = 'var(--theme-text-color)';
    modalBody.style.background = 'transparent';
    modalBody.innerHTML = content;
    modalContent.appendChild(modalBody);
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
    
    // 点击模态框外部关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
            if (onClose && typeof onClose === 'function') {
                onClose();
            }
        }
    });
}

/**
 * 显示模态框
 * @param {Object} options - 模态框选项
 * @param {string} options.title - 标题
 * @param {string|HTMLElement} options.content - 内容 (HTML字符串或DOM元素)
 * @param {Array} options.buttons - 按钮配置 [{text: '确定', class: 'btn-primary', click: function(){}}]
 * @param {boolean} options.closable - 是否可关闭，默认true
 * @param {string} options.size - 尺寸 'small', 'medium', 'large'，默认medium
 * @param {Function} options.onClose - 关闭回调
 * @returns {HTMLElement} 返回模态框元素
 */
function showCommonModal(options = {}) {
    const {
        title = '提示',
        content = '',
        buttons = [{text: '确定', class: 'btn-primary', click: function(){}}],
        closable = true,
        closeOnBackdropClick = true,
        size = 'medium',
        onClose = null
    } = options;

    // 移除已存在的模态框
    const existingModal = document.querySelector('.modal.common-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // 创建模态框结构
    const modal = document.createElement('div');
    modal.className = 'modal common-modal';
    
    // 获取当前主题
    const currentTheme = document.documentElement.getAttribute('data-theme') || 'default';
    modal.classList.add(`theme-${currentTheme}`);
    
    // 设置尺寸
    const sizeClass = {
        small: 'max-width: 360px;',
        medium: 'max-width: 480px;',
        large: 'max-width: 720px;'
    };

    // 检测是否为横屏模式
    const isLandscape = window.innerWidth > window.innerHeight;
    
    // 在横屏模式下增加宽度
    const modalWidth = isLandscape ? {
        small: 'max-width: 480px;',
        medium: 'max-width: 640px;',
        large: 'max-width: 840px;'
    } : sizeClass;

    modal.innerHTML = `
        <div class="modal-content" style="${modalWidth[size] || modalWidth.medium}">
            <div class="modal-header">
                <h2>${title}</h2>
                ${closable ? '<span class="close-modal">&times;</span>' : ''}
            </div>
            <div class="modal-body">
                ${typeof content === 'string' ? content : ''}
            </div>
            <div class="modal-footer">
                ${buttons.map(btn => `
                    <button class="btn ${btn.class || 'btn-secondary'}" data-action="${btn.action || 'custom'}">
                        ${btn.icon ? `<i class="${btn.icon} btn-icon"></i>` : ''}
                        ${btn.text}
                    </button>
                `).join('')}
            </div>
        </div>
    `;

    // 如果content是DOM元素，则直接添加
    if (typeof content !== 'string' && content instanceof HTMLElement) {
        const modalBody = modal.querySelector('.modal-body');
        modalBody.innerHTML = '';
        modalBody.appendChild(content);
    }

    // 添加到页面
    document.body.appendChild(modal);

    // 绑定事件
    const modalContent = modal.querySelector('.modal-content');
    const closeBtn = modal.querySelector('.close-modal');
    const footerButtons = modal.querySelectorAll('.modal-footer .btn');

    // 关闭模态框函数
    function closeModal() {
        modal.style.display = 'none';
        setTimeout(() => {
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        }, 300);
        if (onClose) onClose();
    }

    // 点击背景关闭
    if (closeOnBackdropClick) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal();
            }
        });
    }

    // 关闭按钮事件
    if (closeBtn) {
        closeBtn.addEventListener('click', closeModal);
    }

    // 按钮事件
    footerButtons.forEach((btn, index) => {
        btn.addEventListener('click', function() {
            const action = this.getAttribute('data-action');
            if (action === 'close' || (buttons[index] && buttons[index].close !== false)) {
                closeModal();
            }
            if (buttons[index] && buttons[index].click) {
                buttons[index].click();
            }
        });
    });

    // ESC键关闭
    if (closable) {
        function handleEsc(e) {
            if (e.key === 'Escape') {
                closeModal();
                document.removeEventListener('keydown', handleEsc);
            }
        }
        document.addEventListener('keydown', handleEsc);
    }

    // 显示模态框
    modal.style.display = 'flex';
    
    // 优化横屏模式下的位置，避免被键盘遮挡
    if (isLandscape) {
        const modalContent = modal.querySelector('.modal-content');
        modalContent.style.marginTop = '5vh';
        modalContent.style.maxHeight = '90vh';
        
        // 为表单添加样式，优化在键盘弹出时的显示
        const modalBody = modal.querySelector('.modal-body');
        modalBody.style.maxHeight = '70vh';
        modalBody.style.overflowY = 'auto';
    }

    return modal;
}

/**
 * 显示确认对话框
 * @param {Object} options - 配置选项
 * @param {string} options.title - 标题，默认'确认'
 * @param {string} options.message - 消息内容
 * @param {string} options.confirmText - 确认按钮文本，默认'确定'
 * @param {string} options.cancelText - 取消按钮文本，默认'取消'
 * @param {Function} options.onConfirm - 确认回调
 * @param {Function} options.onCancel - 取消回调
 * @returns {HTMLElement} 返回模态框元素
 */
function showConfirmDialog(options = {}) {
    const {
        title = '确认',
        message = '您确定要执行此操作吗？',
        confirmText = '确定',
        cancelText = '取消',
        onConfirm = null,
        onCancel = null
    } = options;

    return showCommonModal({
        title: title,
        content: `<div class="confirm-dialog"><p>${message}</p></div>`,
        size: 'small',
        buttons: [
            {
                text: cancelText,
                class: 'btn-secondary',
                click: onCancel
            },
            {
                text: confirmText,
                class: 'btn-primary',
                click: onConfirm
            }
        ]
    });
}

/**
 * 显示表单模态框
 * @param {Object} options - 配置选项
 * @param {string} options.title - 标题
 * @param {Array} options.fields - 表单字段配置
 * @param {Object} options.data - 初始数据
 * @param {Function} options.onSubmit - 提交回调
 * @param {Function} options.onCancel - 取消回调
 * @param {string} options.submitText - 提交按钮文本，默认'提交'
 * @param {string} options.cancelText - 取消按钮文本，默认'取消'
 * @param {string} options.layout - 布局 'single'(单列), 'double'(双列), 'auto'(自动)
 * @param {boolean} options.closable - 是否可关闭，默认true
 * @param {boolean} options.closeOnBackdropClick - 是否允许点击背景关闭
 * @returns {HTMLElement} 返回模态框元素
 */
function showFormModal(options = {}) {
    const {
        title = '表单',
        fields = [],
        data = {},
        onSubmit = null,
        onCancel = null,
        submitText = '提交',
        cancelText = '取消',
        layout = 'auto',
        closable = true,
        closeOnBackdropClick = true
    } = options;

    // 创建表单元素
    const formElement = document.createElement('form');
    formElement.className = 'common-form';
    formElement.id = `modal-form-${Date.now()}`;
    
    // 根据屏幕宽度和字段数量决定是否使用双列布局
    const useDoubleColumn = layout === 'double' || 
        (layout === 'auto' && window.innerWidth >= 768 && fields.length >= 3);
    
    // 如果使用双列布局，创建一个容器
    if (useDoubleColumn) {
        formElement.style.display = 'grid';
        formElement.style.gridTemplateColumns = 'repeat(2, 1fr)';
        formElement.style.columnGap = '20px';
    }
    
    // 生成表单字段
    fields.forEach(field => {
        const {
            name,
            label,
            type = 'text',
            required = false,
            placeholder = '',
            options = [],
            value = data[name] || '',
            fullWidth = false,
            noDefaultOption = false
        } = field;
        
        // 创建表单组
        const formGroup = document.createElement('div');
        formGroup.className = 'form-group';
        
        // 如果设置了fullWidth或者是textarea类型，则占据整行
        if (useDoubleColumn && (fullWidth || type === 'textarea')) {
            formGroup.style.gridColumn = '1 / span 2';
        }
        
        // 创建标签
        const labelElement = document.createElement('label');
        labelElement.textContent = label;
        if (required) {
            const requiredSpan = document.createElement('span');
            requiredSpan.style.color = '#ff3b30';
            requiredSpan.textContent = ' *';
            labelElement.appendChild(requiredSpan);
        }
        formGroup.appendChild(labelElement);
        
        // 创建输入元素
        let inputElement;
        
        if (type === 'select') {
            inputElement = document.createElement('select');
            inputElement.name = name;
            if (required) inputElement.required = true;
            
            // 只有当noDefaultOption为false时才添加默认选项
            if (!noDefaultOption) {
                const defaultOption = document.createElement('option');
                defaultOption.value = '';
                defaultOption.textContent = placeholder || '请选择';
                inputElement.appendChild(defaultOption);
            }
            
            // 添加选项
            options.forEach(opt => {
                const option = document.createElement('option');
                const optValue = typeof opt === 'object' ? opt.value : opt;
                const optText = typeof opt === 'object' ? opt.text : opt;
                
                option.value = optValue;
                option.textContent = optText;
                
                // 设置data属性
                if (typeof opt === 'object' && opt.deviceTypeId) {
                    option.setAttribute('data-device-type-id', opt.deviceTypeId);
                }
                
                // 设置选中状态
                if (value === optValue) {
                    option.selected = true;
                }
                
                inputElement.appendChild(option);
            });
            
            // 如果没有选中任何选项且有选项可选，默认选中第一个
            if (inputElement.selectedIndex === -1 && options.length > 0 && noDefaultOption) {
                inputElement.selectedIndex = 0;
            }
        } else if (type === 'textarea') {
            inputElement = document.createElement('textarea');
            inputElement.name = name;
            inputElement.placeholder = placeholder || '';
            inputElement.value = value;
            if (required) inputElement.required = true;
        } else {
            inputElement = document.createElement('input');
            inputElement.type = type;
            inputElement.name = name;
            inputElement.placeholder = placeholder || '';
            inputElement.value = value;
            if (required) inputElement.required = true;
        }
        
        formGroup.appendChild(inputElement);
        
        // 创建错误消息元素
        const errorSpan = document.createElement('span');
        errorSpan.className = 'form-error';
        errorSpan.style.display = 'none';
        formGroup.appendChild(errorSpan);
        
        formElement.appendChild(formGroup);
    });
    
    console.log("创建表单模态框，字段数:", fields.length, "布局:", useDoubleColumn ? "双列" : "单列");
    
    // 创建模态框
    const modal = showCommonModal({
        title: title,
        content: formElement,
        closable: closable,
        closeOnBackdropClick: closeOnBackdropClick,
        buttons: [
            {
                text: cancelText,
                class: 'btn-secondary',
                click: function() {
                    console.log("取消按钮被点击");
                    if (typeof onCancel === 'function') {
                        onCancel();
                    }
                }
            },
            {
                text: submitText,
                class: 'btn-primary',
                click: function() {
                    console.log("提交按钮被点击");
                    
                    // 手动验证表单
                    let isValid = true;
                    const formData = {};
                    
                    formElement.querySelectorAll('.form-group').forEach(group => {
                        const input = group.querySelector('input, select, textarea');
                        const errorSpan = group.querySelector('.form-error');
                        
                        // 重置错误状态
                        group.classList.remove('error');
                        errorSpan.style.display = 'none';
                        errorSpan.textContent = '';
                        
                        // 验证必填字段
                        if (input.required && !input.value.trim()) {
                            group.classList.add('error');
                            errorSpan.textContent = '此字段为必填项';
                            errorSpan.style.display = 'block';
                            isValid = false;
                        } 
                        // 验证邮箱格式
                        else if (input.type === 'email' && input.value && !isValidEmail(input.value)) {
                            group.classList.add('error');
                            errorSpan.textContent = '请输入有效的邮箱地址';
                            errorSpan.style.display = 'block';
                            isValid = false;
                        }
                        // 验证电话号码格式
                        else if (input.type === 'tel' && input.value && !isValidPhone(input.value)) {
                            group.classList.add('error');
                            errorSpan.textContent = '请输入有效的电话号码';
                            errorSpan.style.display = 'block';
                            isValid = false;
                        }
                        
                        // 收集表单数据
                        formData[input.name] = input.value;
                        
                        // 特殊处理select元素的data属性
                        if (input.tagName === 'SELECT' && input.selectedIndex >= 0) {
                            const selectedOption = input.options[input.selectedIndex];
                            const deviceTypeId = selectedOption.getAttribute('data-device-type-id');
                            if (deviceTypeId) {
                                formData.deviceTypeId = deviceTypeId;
                            }
                        }
                    });
                    
                    if (isValid) {
                        console.log("表单验证通过，数据:", formData);
                        if (typeof onSubmit === 'function') {
                            onSubmit(formData);
                        } else {
                            console.warn("onSubmit回调未定义");
                            closeModal(modal);
                        }
                    } else {
                        console.warn("表单验证失败");
                    }
                }
            }
        ]
    });
    
    // 阻止表单默认提交行为
    formElement.addEventListener('submit', function(e) {
        e.preventDefault();
        console.log("表单提交事件被拦截");
    });
    
    return modal;
}

/**
 * 显示信息提示框
 * @param {string} message - 消息内容
 * @param {string} type - 类型 'info', 'success', 'warning', 'error'
 * @param {Function} onClose - 关闭回调
 */
function showInfoDialog(message, type = 'info', onClose = null) {
    const icons = {
        info: 'ℹ️',
        success: '✅',
        warning: '⚠️',
        error: '❌'
    };

    const colors = {
        info: 'var(--theme-gradient-start)',
        success: '#34C759',
        warning: '#FF9500',
        error: '#FF3B30'
    };

    return showCommonModal({
        title: type.charAt(0).toUpperCase() + type.slice(1),
        content: `
            <div style="text-align: center; padding: 16px 0;">
                <div style="font-size: 48px; margin-bottom: 16px;">${icons[type]}</div>
                <p style="font-size: 16px; margin: 0; color: var(--theme-text-color);">${message}</p>
            </div>
        `,
        size: 'small',
        buttons: [
            {
                text: '确定',
                class: 'btn-primary',
                click: onClose
            }
        ]
    });
}

/**
 * 显示加载模态框
 * @param {string} message - 加载消息，默认'加载中...'
 * @returns {HTMLElement} 返回模态框元素
 */
function showLoadingModal(message = '加载中...') {
    return showCommonModal({
        title: '',
        content: `
            <div style="text-align: center; padding: 32px 16px;">
                <div class="spinner" style="margin: 0 auto 20px;"></div>
                <p style="margin: 0; color: var(--theme-text-color); opacity: 0.8;">${message}</p>
            </div>
        `,
        size: 'small',
        closable: false,
        buttons: []
    });
}

/**
 * 关闭模态框
 * @param {HTMLElement} modal - 模态框元素，如果不传则关闭所有模态框
 */
function closeModal(modal = null) {
    if (modal) {
        modal.style.display = 'none';
        setTimeout(() => {
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        }, 300);
    } else {
        // 关闭所有模态框
        const modals = document.querySelectorAll('.modal');
        modals.forEach(m => {
            m.style.display = 'none';
            setTimeout(() => {
                if (m.parentNode) {
                    m.parentNode.removeChild(m);
                }
            }, 300);
        });
    }
}

/**
 * 验证邮箱格式
 */
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

/**
 * 验证电话号码格式
 */
function isValidPhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

/**
 * 显示空数据状态
 * @param {Object} options - 配置选项
 * @param {HTMLElement|string} options.container - 容器元素或容器ID
 * @param {string} [options.message='暂无数据'] - 显示的消息
 * @param {string} [options.icon='layui-icon-about'] - 图标类名 (使用layui图标)
 * @param {string} [options.iconColor='#fac858'] - 图标颜色
 * @param {boolean} [options.clearContainer=false] - 是否清空容器内容
 * @param {Function} [options.onRender] - 渲染后的回调函数
 * @param {string} [options.size='medium'] - 尺寸，可选值：'small', 'medium', 'large', 'custom'
 * @param {string} [options.minWidth] - 最小宽度，如 '300px'（size为'custom'时有效）
 * @param {string} [options.padding] - 内边距，如 '40px 70px'（size为'custom'时有效）
 * @param {string} [options.iconSize] - 图标大小，如 '48px'（size为'custom'时有效）
 * @param {string} [options.fontSize] - 字体大小，如 '18px'（size为'custom'时有效）
 * @returns {HTMLElement} 返回创建的空状态元素
 */
function showEmptyState(options = {}) {
    // 处理默认选项
    const {
        container,
        message = '暂无数据',
        icon = 'layui-icon-about',
        iconColor = '#fac858',
        clearContainer = false,
        onRender = null,
        size = 'medium',
        minWidth,
        padding,
        iconSize,
        fontSize
    } = options;

    // 获取容器元素
    let containerElement = null;
    if (typeof container === 'string') {
        containerElement = document.getElementById(container);
    } else if (container instanceof HTMLElement) {
        containerElement = container;
    }

    if (!containerElement) {
        console.error('无效的容器元素');
        return null;
    }

    // 如果需要清空容器
    if (clearContainer) {
        containerElement.innerHTML = '';
    }

    // 确保容器有相对或绝对定位，以便正确定位空状态元素
    const containerPosition = window.getComputedStyle(containerElement).position;
    if (containerPosition === 'static') {
        containerElement.style.position = 'relative';
    }

    // 根据尺寸设置样式
    let sizeStyles = {};
    let iconSizeValue = '48px';
    let fontSizeValue = '18px';
    let marginBottomValue = '20px';
    
    // 根据预设尺寸设置样式
    switch (size) {
        case 'small':
            sizeStyles = {
                padding: '20px 40px',
                minWidth: '200px'
            };
            iconSizeValue = '36px';
            fontSizeValue = '16px';
            marginBottomValue = '15px';
            break;
        case 'large':
            sizeStyles = {
                padding: '50px 80px',
                minWidth: '350px'
            };
            iconSizeValue = '64px';
            fontSizeValue = '20px';
            marginBottomValue = '25px';
            break;
        case 'custom':
            // 使用自定义尺寸
            if (padding) sizeStyles.padding = padding;
            if (minWidth) sizeStyles.minWidth = minWidth;
            iconSizeValue = iconSize || '48px';
            fontSizeValue = fontSize || '18px';
            break;
        default: // medium 或其他
            sizeStyles = {
                padding: '40px 70px',
                minWidth: '300px'
            };
            break;
    }

    // 创建空状态元素
    const emptyStateElement = document.createElement('div');
    emptyStateElement.className = 'empty-state';
    
    // 设置基本样式
    Object.assign(emptyStateElement.style, {
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(47, 64, 113, 0.9)',
        borderRadius: '10px',
        zIndex: '10',
        color: '#e0e0e0',
        textAlign: 'center',
        boxShadow: '0 4px 16px rgba(0, 0, 0, 0.2)',
        border: '1px solid rgba(60, 120, 230, 0.3)',
        transition: 'opacity 0.3s ease'
    });
    
    // 应用尺寸相关样式
    Object.assign(emptyStateElement.style, sizeStyles);

    // 设置内容
    emptyStateElement.innerHTML = `
        <i class="layui-icon ${icon}" style="font-size: ${iconSizeValue}; color: ${iconColor}; margin-bottom: ${marginBottomValue};"></i>
        <p style="margin: 0; font-size: ${fontSizeValue}; line-height: 1.5;">${message}</p>
    `;

    // 添加到容器
    containerElement.appendChild(emptyStateElement);

    // 触发渲染回调
    if (typeof onRender === 'function') {
        onRender(emptyStateElement);
    }

    return emptyStateElement;
}

/**
 * 隐藏空状态元素
 * @param {HTMLElement} emptyStateElement - 由showEmptyState创建的元素
 * @param {boolean} [remove=true] - 是否从DOM中移除元素
 */
function hideEmptyState(emptyStateElement, remove = true) {
    if (!emptyStateElement || !emptyStateElement.classList.contains('empty-state')) {
        return;
    }

    emptyStateElement.style.opacity = '0';

    if (remove) {
        setTimeout(() => {
            if (emptyStateElement.parentNode) {
                emptyStateElement.parentNode.removeChild(emptyStateElement);
            }
        }, 300);
    }
}

// 将所有UI组件功能导出到全局对象
window.showToast = showToast;
window.showModal = showModal;
window.showCommonModal = showCommonModal;
window.showConfirmDialog = showConfirmDialog;
window.showFormModal = showFormModal;
window.showInfoDialog = showInfoDialog;
window.showLoadingModal = showLoadingModal;
window.closeModal = closeModal;
window.showEmptyState = showEmptyState;
window.hideEmptyState = hideEmptyState;
